<?php

/**
 * 日志类
 */
class logModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->base->in_logDb();
        $this->base->in_readDb();
        $this->logDb = &$this->base->logDb;
        $this->readDb = &$this->base->readDb;
        $this->redis = & $this->base->redis;
        $this->im = & $this->base->im;
        //$this->im = new IM('n19jmcy59fdd9','BEHIJ6Xx6R2k');
        $this->download_path = $this->base->config['log-dir'].'imLog/';
    }
    /* 记录日志*/
    public function writeLog($dirname = '', $content, $filename = '')
    {
        $result = false;

        if(!$dirname || stripos($dirname, '.') !== false || stripos($dirname, '//') !== false)
        {
            return $result;
        }
        // 删除目录名是否前后的 /
        $dirname = trim($dirname, '/');
        $dirname .= '/';

        $path = $this->base->config['log-dir'].$dirname;
        !file_exists($path) && mkdir($path);
        if(!$filename)
        {
            $filename = date('Ymd').'.txt';
        }
        
        $fp = fopen($path.$filename, "a");

        $result = fwrite($fp, $content) !== false;
        fclose($fp);

        return $result;
    }
    /**
     * 接口访问记录
     * @return array
     */
    public function apiVisitRecord()
    {
        $resEndTime = microtime(TRUE);
        $resTime = intval(($resEndTime - $this->base->microtime) * 1000);
        $uid = intval($this->base->uid);
        $xuid = intval(common::request('xuid', 'R'));

        $apiData = array(
            'time'  => time(),
            'c'     => common::request('c','R'),
            'a'     => common::request('a','R'),
            'type'     => $this->base->projectId,
            'version'     => $this->base->vn,
            'uid'   => intval($uid),
            'xuid' => $xuid,
            'cid'   => $this->base->cid,
            'resTime'   => $resTime,
            'area' => '',
        );

        empty($this->db) && $this->base->in_db();
        $this->db->insertRowTable('d_api', $apiData);

        $logInfo = array(
            'et' => 'ijoggers-api',
            'vtm' => round(microtime(TRUE) * 1000),
            'body' => $apiData,
        );

        $this->writeLog('api', json_encode($logInfo) . "\n", 'api.log');
        
        //写入redis
        $as = [
            'postData','getCommentList','post','publishComment','likePost','upComment','lightenComment',
            'register','login','firstBindSocialUser','bindSocialUser','bindPhone','getUserCenterInfo',
            'handleActivity','createGroup','dismiss','applyGroup','quit','search','createActivity',
            'runningData','DelRunningData','delRunData'
        ];
        if(in_array($apiData['a'],$as)){
            //统计需要额外数据
            $addons = [
                'postData' => 'news_id', //查看
                'getCommentList' => 'news_id', //查看
                'post' => 'boardId', //发帖
                'publishComment' => 'news_id', //评论
                'likePost' => 'news_id', //点赞
                'upComment' => 'comment_id', //点亮评论
                'lightenComment' => 'comment_id', //点亮评论
                'handleActivity' => 'type', //参加或退出活动
                'firstBindSocialUser' => 'type', //绑定社交渠道
                'bindSocialUser' => 'type', //绑定社交渠道
                'getUserCenterInfo' => 'uid', //空间访问数
                'quit' => 'gid', //退出群组
                'createActivity' => 'gid', //创建群组活动
                'applyGroup' => 'gid', //加群
            ];
            
            if(in_array($apiData['a'],array_keys($addons))){
                $apiData['addon'] = common::request($addons[$apiData['a']], 'R');
                if(!isset($apiData['addon']) || $apiData['addon']===''){
                    return;
                }
            }
            $apiData['ip'] = common::getip();
            if(!is_object($this->redis)){
                $this->base->in_redis();
            }
            $this->redis->rpush(REDIS_PREFIX.'ApiVisit',json_encode($apiData));
            //$this->logDb->insertRowTable('d_api',$apiData);
        }

        return true;
    }
    /**
     * 接口返回空数据日志
     * @return
     */
    public function emptyResponseRecord()
    {
        $emptyKey = '';

        $rel = isset($this->base->result['result']) ? $this->base->result['result'] : NULL;
        if(is_array($rel))
        {
            foreach ($rel as $k => $v)
            {
                if(is_array($v) && empty($v))
                {
                    $emptyKey .= $k.',';
                }
            }
        }
        if($emptyKey)
        {
            $logInfo = '['.date('Y-m-d H:i:s')."]\t".$emptyKey."\t";
            $params = array_merge($_GET, $_POST);
            $params = str_replace(' ', '', $params);
            $params = str_replace("\n", '', $params);
            $params = urldecode(http_build_query($params, NULL, '&'));

            $logInfo .= $params."\n";
            $this->writeLog('empty-response', $logInfo, 'empty.txt');
        }

        return true;
    }
    
    /*
     * 保存api访问统计
     */
    public function countApiVisitRecord(){
        $now = time();
        $oneHourAgo = $now - 3600;
        
        $news_mod = $this->base->load('news');
        //$rows = $this->logDb->getAll("SELECT * FROM d_api WHERE `time` BETWEEN $oneHourAgo AND $now");
        $redisKey = REDIS_PREFIX.'ApiVisit';
        $rows = $this->redis->lrange($redisKey,0,-1);
        $new_rows = [];
        $res = $this->readDb->getAll('SELECT gid FROM r_admin_concern_group');
        $concern_groups = [];
        foreach($res as $row){
            $concern_groups[] = $row['gid'];
        }
        $implode_concern_groups = implode(',',$concern_groups);
        
        $uids = ['postData'=>[],'getCommentList'=>[],'post'=>[],'publishComment'=>[],'runningData'=>[],'applyGroup'=>[],'quit'=>[]];
        $likePost_uids = [];
        $upComment_uids = [];
        $runningData_uids = [];
        //不需访问数据库
        foreach($rows as $row){
            $row = json_decode($row,true);
            $a = $row['a'];
            
            //点击数
            //评论
            //点赞
            if($a == 'postData'
            || $a == 'getCommentList'
            || $a == 'publishComment'
            || $a == 'likePost'
            ){
                $post = $news_mod->getRawNewsInfo($row['addon']);
                $tag = $post['board'];
                //点击人数
                $_uids = &$uids[$a];
                !isset($_uids[$tag]) && $_uids[$tag] = [];
                if(!in_array($row['uid'],$_uids[$tag])){
                    if(isset($new_rows[$a.'_user'][$tag])){
                        $new_rows[$a.'_user'][$tag]++;
                    }else{
                        $new_rows[$a.'_user'][$tag]=1;
                    }
                    $_uids[$tag][] = $row['uid'];
                }
                //点击总人数
                !isset($_uids['all']) && $_uids['all'] = [];
                if(!in_array($row['uid'],$_uids['all'])){
                    if(isset($new_rows[$a.'_user']['all'])){
                        $new_rows[$a.'_user']['all']++;
                    }else{
                        $new_rows[$a.'_user']['all']=1;
                    }
                    $_uids['all'][] = $row['uid'];
                }
                //点击数
                if(isset($new_rows[$a][$tag])){
                    $new_rows[$a][$tag]++;
                }else{
                    $new_rows[$a][$tag] = 1;
                }
            }
            
            //发帖数
            elseif($a == 'post'){
                $boardId = $row['addon'];
                //发帖人数
                !isset($post_uids[$boardId]) && $post_uids[$boardId] = [];
                if(!in_array($row['uid'],$post_uids[$boardId])){
                    if(isset($new_rows['post_user'][$boardId])){
                        $new_rows['post_user'][$boardId]++;
                    }else{
                        $new_rows['post_user'][$boardId]=1;
                    }
                    
                    $post_uids[$boardId][] = $row['uid'];
                }
                //发帖总人数
                !isset($post_uids['all']) && $post_uids['all'] = [];
                if(!in_array($row['uid'],$post_uids['all'])){
                    if(isset($new_rows['post_user']['all'])){
                        $new_rows['post_user']['all']++;
                    }else{
                        $new_rows['post_user']['all']=1;
                    }
                    $post_uids['all'][] = $row['uid'];
                }
                //发帖数
                if(isset($new_rows['post'][$boardId])){
                    $new_rows['post'][$boardId]++;
                }else{
                    $new_rows['post'][$boardId]=1;
                }
            }
            
            //点亮数
            elseif($a == 'lightenComment'
                || $a == 'upComment'
            ){
                $post = $news_mod->getNewsByComment($row['addon']);
                $tag = $post['board'];
                //点亮人数
                !isset($upComment_uids[$tag]) && $upComment_uids[$tag] = [];
                if(!in_array($row['uid'],$upComment_uids[$tag])){
                    if(isset($new_rows['upComment_user'][$tag])){
                        $new_rows['upComment_user'][$tag]++;
                    }else{
                        $new_rows['upComment_user'][$tag]=1;
                    }
                    $upComment_uids[$tag][] = $row['uid'];
                }
                //点亮总人数
                !isset($upComment_uids['all']) && $upComment_uids['all'] = [];
                if(!in_array($row['uid'],$upComment_uids['all'])){
                    if(isset($new_rows['upComment_user']['all'])){
                        $new_rows['upComment_user']['all']++;
                    }else{
                        $new_rows['upComment_user']['all']=1;
                    }
                    $upComment_uids['all'][] = $row['uid'];
                }
                //点亮数
                if(isset($new_rows['upComment'][$tag])){
                    $new_rows['upComment'][$tag]++;
                }else{
                    $new_rows['upComment'][$tag]=1;
                }
            }
            
            //参加活动(tag=1)，退出活动(tag=2)
            elseif($a == 'handleActivity'){
                switch($row['addon']){
                    case 1:
                        $tag = 'join';
                        break;
                    case 2:
                        $tag = 'quit';
                        break;
                    case 3:
                        $tag = 'cancel';
                }
                if(!isset($new_rows[$a][$tag])){
                    $new_rows[$a][$tag] = 1;
                }else{
                    $new_rows[$a][$tag]++;
                }
            }
            
            //注册 android(type=1),ios(type=2)
            elseif($a == 'register'
                || $a == 'login'
            ){
                //按设备区分
                $tag = $row['type'] == 1 ? 'android':'ios';
                if(isset($new_rows[$a.'_'.$tag][$a.'_'.$tag])){
                    $new_rows[$a.'_'.$tag][$a.'_'.$tag]++;
                }else{
                    $new_rows[$a.'_'.$tag][$a.'_'.$tag]=1;
                }
                
                //总人数
                if(isset($new_rows[$a][$a.'_all'])){
                    $new_rows[$a][$a.'_all']++;
                }else{
                    $new_rows[$a][$a.'_all']=1;
                }

                //按版本区分
                $tag = $a=='login' ? 'lv':'rv';
                if(isset($new_rows[$a][$tag.$row['version']])){
                    $new_rows[$a][$tag.$row['version']]++;
                }else{
                    $new_rows[$a][$tag.$row['version']]=1;
                }
                
                //按城市区分的注册人数
                if($a == 'register'){
                    $city = $this->base->load('ip')->find($row['ip']);
                    $city = $city[2] ? $city[2] : '其他';
                    if(isset($new_rows['register_city'][$city])){
                        $new_rows['register_city'][$city]++;
                    }else{
                        $new_rows['register_city'][$city]=1;
                    }
                }
            }
            
            //绑定社交渠道
            elseif($a == 'firstBindSocialUser'
                || $a == 'bindSocialUser'
            ){
                $tag = 'c'.$row['addon'];
                if(isset($new_rows['bindSocialUser'][$tag])){
                    $new_rows['bindSocialUser'][$tag]++;
                }else{
                    $new_rows['bindSocialUser'][$tag]=1;
                }
                if(isset($new_rows['bindSocialUser']['all'])){
                    $new_rows['bindSocialUser']['all']++;
                }else{
                    $new_rows['bindSocialUser']['all']=1;
                }
            }
            
            //访问空间
            elseif($a == 'getUserCenterInfo'){
                //访问他人空间
                if($row['addon'] == $row['uid']){
                    if(isset($new_rows[$a]['other'])){
                        $new_rows[$a]['other']++;
                    }else{
                        $new_rows[$a]['other']=1;
                    }
                }
                //总空间访问
                if(isset($new_rows[$a]['all'])){
                    $new_rows[$a]['all']++;
                }else{
                    $new_rows[$a]['all']=1;
                }
            }
            
            //新增跑步记录
            elseif($a == 'runningData'){
                if(!in_array($row['uid'],$uids[$a])){
                    //按城市区分的人数
                    $city = $this->base->load('ip')->find($row['ip']);
                    $city = $city[2] ? $city[2] : '其他';
                    if(isset($new_rows[$a.'_city'][$city])){
                        $new_rows[$a.'_city'][$city]++;
                    }else{
                        $new_rows[$a.'_city'][$city]=1;
                    }
                    
                    $uids[$a][] = $row['uid'];
                }
                
                //总记录数
                if(isset($new_rows[$a])){
                    $new_rows[$a]++;
                }else{
                    $new_rows[$a]=1;
                }
            }
            
            //创建活动
            //申请加入
            //退出
            elseif($a == 'createActivity'
                || $a == 'applyGroup'
                || $a == 'quit'
            ){
                $gid = $row['addon'];
                //是关注的群
                if(in_array($gid,$concern_groups)){
                    if(isset($new_rows[$a.'_group'][$gid])){
                        $new_rows[$a.'_group'][$gid]++;
                    }else{
                        $new_rows[$a.'_group'][$gid]=1;
                    }
                }
                
                if(isset($new_rows[$a])){
                    $new_rows[$a]++;
                }else{
                    $new_rows[$a] = 1;
                }
            }
            
            else{
                /*
                $row['a'] == 'createGroup' //新增群组
                $row['a'] == 'dismiss' //解散群组
                $row['a'] == 'search' //搜索活动
                $row['a'] == 'DelRunningData' //用户删除跑步记录
                $row['a'] == 'delRunData' // 运营删除跑步记录
                $a == 'bindPhone'  //绑定手机
                */
                if(isset($new_rows[$a])){
                    $new_rows[$a]++;
                }else{
                    $new_rows[$a] = 1;
                }
            }
        }
        
        //需要访问数据库
        //用户-----------------------------------------
        //按渠道统计新增游客
        $sql = "SELECT count(*) as sum,type FROM r_visitor WHERE addtime BETWEEN $oneHourAgo AND $now GROUP BY type";
        $res = $this->readDb->getAll($sql);
        foreach($res as $row){
            $a = 'visitor_';
            $a .= $row['type']==1 ? 'android' : 'ios';
            $new_rows[$a] = $row['sum'];
        }
        
        //按版本统计新增游客
        $sql = "SELECT count(*) as sum,version FROM r_visitor WHERE addtime BETWEEN $oneHourAgo AND $now GROUP BY version";
        $res = $this->readDb->getAll($sql);
        foreach($res as $row){
            $new_rows['visitor']['v'.$row['version']] = $row['sum'];
        }
        
        //跑步记录-------------------------------------
        //异常记录数
        $sql = "SELECT count(*) AS sum FROM r_data WHERE overSpeed!=0 AND updatetime BETWEEN $oneHourAgo AND $now";
        $res = $this->readDb->getRow($sql);
        $res['sum'] && $new_rows['runningData_overSpeed'] = $res['sum'];
        
        //新增总里程，总时长
        $sql = "SELECT sum(round(mileage,3)) as mileage, sum(round(elapsedtime,3))/3600 as elapsedtime from r_data WHERE addtime BETWEEN $oneHourAgo AND $now";
        $res = $this->readDb->getRow($sql);
        !$res['mileage'] && $res['mileage']=0;
        !$res['elapsedtime'] && $res['elapsedtime']=0;
        $res['mileage'] && $res['elapsedtime'] && $new_rows['runningData_sum'] = $res;
        
        //关注的群-------------------------------------
        if($implode_concern_groups){
            //发帖数
            $sql = "SELECT count(*) as sum,gid FROM r_group_news WHERE gid IN($implode_concern_groups) AND addtime BETWEEN $oneHourAgo AND $now GROUP BY gid";
            $res = $this->readDb->getAll($sql);
            foreach($res as $row){
                $new_rows['runningData_group'][$row['gid']] = $row['sum'];
            }
            
            //跑步数
            $sql = "SELECT count(*) as sum,gid FROM r_group_run WHERE gid IN($implode_concern_groups) AND addtime BETWEEN $oneHourAgo AND $now GROUP BY gid";
            $res = $this->readDb->getAll($sql);
            foreach($res as $row){
                $new_rows['post_group'][$row['gid']] = $row['sum'];
            }
        }
        
        //写入数据-----------------------------------
        foreach($new_rows as $a=>$v){
            $data = [
                'a' => $a,
                'value' => is_array($v) ? json_encode($v) : $v,
                'add_time' => $now
            ];
            $this->logDb->insertRowTable('d_api_count',$data);
        }
        $this->redis->del($redisKey);
        
        //写入每小时天气数据-------------------------
        $weather = $this->base->load('weather');
        $cityList = $weather->getAllCity();
        foreach($cityList as $row){
            $data = $weather->getWeatherInfo($row['city_id']);
            $new_data = [
                'city'=>$data['city_name'],
                'weather'=>$data['text'],
                'temperature'=>$data['temperature'],
                'pm25'=>$data['pm25'],
                'addtime'=>$now,
            ];
            $this->logDb->insertRowTable('r_log_weather',$new_data);
        }
    }
    
    public function countApiVisitRecordOnce(){
        $now = time();
        $sevenDaysAgo = $now - 7*24*3600;
        $todayBegin = $now-24*3600;
        
        //群组-----------------------------------------
        //正常，已删
        $sql = "SELECT count(*) as sum, count(DISTINCT uid) as uid_sum, is_delete FROM r_group_run WHERE addtime BETWEEN $sevenDaysAgo AND $now GROUP BY is_delete";
        $res = $this->db->getAll($sql);
        foreach($res as $row){
            $tag = $row['is_delete'] ? 'is_delete' : 'nomal';
            $new_rows['groupRun'][$tag] = $row['sum'];
            $new_rows['groupRun'][$tag.'_user'] = $row['uid_sum'];
        }
        
        //异常
        $sql = "SELECT count(*) as sum, count(DISTINCT r_group_run.uid) as uid_sum FROM r_group_run LEFT JOIN r_data ON r_data.did = r_group_run.did WHERE r_group_run.addtime BETWEEN $sevenDaysAgo AND $now AND r_data.overSpeed=1";
        $res = $this->db->getRow($sql);
        $new_rows['groupRun']['overSpeed'] = $res['sum'];
        $new_rows['groupRun']['overSpeed_user'] = $res['uid_sum'];

        //各状态活动数
        $sql = "SELECT count(*) as sum,status FROM r_group_activity WHERE addtime BETWEEN $todayBegin AND $now GROUP BY status";
        $res = $this->db->getAll($sql);
        foreach($res as $row){
            $new_rows['createActivity']['s'.$row['status']] = $row['sum'];
        }
    
        //跑步----------------------------------
        //统计7天总数
        //近7天内有一次跑步记录的用户
        //近7天内有两次跑步记录的用户
        //近7天内有两次以上跑步记录用户数
        //近7天内连续两天跑步用户数
        //近7天连续两天以上跑步用户数
        $now_Ymd = date('Ymd',$now);
        $sevenDaysAgo_Ymd = date('Ymd',$sevenDaysAgo);
        $sql = "SELECT date,uid FROM r_data_day WHERE date BETWEEN $sevenDaysAgo_Ymd AND $now_Ymd ORDER BY date";
        $res = $this->db->getAll($sql);
        
        $once = 0;
        $twice = 0;
        $more = 0;
        $twice_consecutive = 0;
        $more_consecutive = 0;
        $uids = [];
        foreach($res as $row){
            $uids[$row['uid']][] = strtotime($row['date']);
        }
        foreach($uids as $uid=>$dates){
            $times = count($dates);
            switch($times){
                case 1: $once++;break;
                case 2: $twice++;break;
                default: $more++;break;
            }
            if($times>1){
                $consecutive_times = 1;
                for($i=0;$i<$times-1;$i++){
                    $consecutive_times = $dates[$i]+24*3600 == $dates[$i+1] ? $consecutive_times+1 : 1;
                }
                if($consecutive_times==2){
                    $twice_consecutive++;
                }elseif($consecutive_times>2){
                    $more_consecutive++;
                }
            }
        }
        
        $new_rows['runningData_user'] = compact('once','twice','more','twice_consecutive','more_consecutive');
        
        //新增设备，统计当天总数
        $tags = [1=>'android',2=>'ios'];
        $sql = "SELECT count(cid) AS sum,client_type FROM r_client WHERE first_visit >= $todayBegin GROUP BY client_type";
        $res = $this->db->getAll($sql);
        foreach($res as $row){
            $new_rows['new_client']['new_client_'.$tags[$row['client_type']]] = $row['sum'];
        }
        
        //日活设备，统计当天总数
        $sql = "SELECT count(cid) AS sum,client_type FROM r_client WHERE last_visit >= $todayBegin GROUP BY client_type";
        $res = $this->db->getAll($sql);
        foreach($res as $row){
            $new_rows['active_client']['active_client_'.$tags[$row['client_type']]] = $row['sum'];
        }
        
        //写入数据
        foreach($new_rows as $a=>$v){
            $data = [
                'a' => $a,
                'value' => is_array($v) ? json_encode($v) : $v,
                'add_time' => $now
            ];
            $this->logDb->insertRowTable('d_api_count',$data);
        }
    }
    
    /*
     * 统计聊天记录
     */
    public function countIMRecord(){
        //0点以后启动，记录昨天数据
        $now = time();
        $yesterday = date('Ymd',strtotime('-1 day'));
        $filenames = [];
        $root_download_path = $this->download_path;
        $this->download_path = $this->download_path.'/'.$yesterday;
        !is_dir($this->download_path) && mkdir($this->download_path);
        
        for($i=0;$i<24;$i++){
            $H = $i<10 ? '0'.$i : $i;
            $filename = $this->downloadHistory($yesterday.$H);
            $filename && $filenames[] = $filename;
        }
        
        $uids = []; //发消息人数
        $message_count = 0; //消息总数
        $push_count = 0; //分发消息
        foreach($filenames as $filename){
            try{
                $zip = zip_open($this->download_path.'/'.$filename);
                if($zip){
                    $zip_entry = zip_read($zip);
                    if(zip_entry_open($zip,$zip_entry)){
                        $content = zip_entry_read($zip_entry,zip_entry_filesize($zip_entry));
                        zip_entry_close($zip_entry);
                    }
                    zip_close($zip);
                }else{
                    throw new Exception('文件无效');
                }
            }catch(Exception $e){
                print_r($e->getMessage());
            }
            if(!$content){
                continue;
            }
            $lines = explode("\n",$content);
            
            $message_count += count($lines)-1;
            foreach($lines as $k=>$line){
                if(!$line){
                    continue;
                }
                $log = json_decode(substr($line,19),false);
                switch($log->targetType){
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        $uids[$log->fromUserId] = '';
                        break;
                    case 6:
                        $push_count++;
                        break;
                    case 5:
                    case 7:
                    case 8:
                }
            }
        }
        $uid_count = count($uids);
        $value = compact('uid_count','message_count','push_count');
        $data = [
            'a' => 'im',
            'value' => json_encode($value),
            'add_time' => $now
        ];
        $this->logDb->insertRowTable('d_api_count',$data);
        
        //删除过去文件
        $threeDaysAgo = date('Ymd',$now-90*24*3600);
        $old_dir = $root_download_path.'/'.$threeDaysAgo;
        if(!is_dir($old_dir)){
            return;
        }
        $dh = opendir($old_dir);
        while($file=readdir($dh)){
            if($file!="." && $file!=".."){
                unlink($old_dir.'/'.$file);
            }
        }
        closedir($dh);
        rmdir($old_dir);
    }
    
    /*
     * 下载聊天记录
     */
    private function downloadHistory($data){
        //消息延迟一小时生成
        $params = ['date' => $data];
        try{
            $ret = $this->im->curl('/message/history',$params);
            if(empty($ret))
                throw new Exception('请求失败');
        }catch(Exception $e){
            print_r($e->getMessage());
        }
        $ret = json_decode($ret);
        
        $filename = basename($ret->url);
        if($filename){
            $download_file = $this->download_path.'/'.$filename;
            copy($ret->url,$download_file);
        }
        return $filename;
    }
    
    /*
     * 获取关注的群
     */
    public function getConcernGroups(){
        return $this->db->getAll('SELECT gid FROM r_admin_concern_group');
    }
    
    /*
     * 获取时段内基于天气的统计数据
     * {
     *   date:{
     *     weather_city:{
     *                     '晴':{
     *                        'cityes':[],
     *                        'register_city':number,
     *                       'runningData_city':number
     *                       },
     *                   '雨'
     *              }
     *     temperature_city,
     *     pm25_city,
     *  }
     * }
     */
    public function getWeatherReport($startTime,$endTime){
        $weather_city = [];
        $temperature_city = [];
        $pm25_city = [];
        //将城市按天气归类
        $sql = "SELECT * FROM r_log_weather WHERE addtime BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);
        foreach($rows as $row){
            $weather_city[$row['weather']]['cities'][$row['city']] = $row['city'];
            
            if($row['temperature']<5){
                $temperature_city['below5']['cities'][$row['city']] = $row['city'];
            }elseif($row['temperature']>=5 && $row['temperature']<15){
                $temperature_city['5-15']['cities'][$row['city']] = $row['city'];
            }elseif($row['temperature']>=15 && $row['temperature']<25){
                $temperature_city['15-25']['cities'][$row['city']] = $row['city'];
            }else{
                $temperature_city['over25']['cities'][$row['city']] = $row['city'];
            }
            
            if($row['pm25']<100){
                $pm25_city['under100']['cities'][$row['city']] = $row['city'];
            }elseif($row['pm25']>=100 && $row['pm25']<200){
                $pm25_city['100-200']['cities'][$row['city']] = $row['city'];
            }else{
                $pm25_city['over200']['cities'][$row['city']] = $row['city'];
            }
        }
        
        $titles = [
            'register_city'=>'注册',
            'runningData_city'=>'跑步',
        ];
        
        //将跑步数据按城市归类
        $cities = [];
        $sql = "SELECT * FROM d_api_count WHERE a IN('register_city','runningData_city') AND add_time BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);
        foreach($rows as $row){
            //$tag = $titles[$row['a']];
            $tag = $row['a'];
            $values = json_decode($row['value']);
            foreach($values as $city=>$value){
                if(isset($cities[$city][$tag])){
                    $cities[$city][$tag] += $value;
                }else{
                    $cities[$city][$tag] = $value;
                }
            }
        }
        
        //合并数据
        foreach($cities as $city=>&$values){
            $weather_arr = [];
            $temperature_arr = [];
            $pm25_arr = [];
            foreach($values as $tag=>&$value){
                foreach($weather_city as $weather => &$v){
                    if(in_array($city,$v['cities'])){
                        if(isset($v[$tag])){
                            $v[$tag]+=$value;
                        }else{
                            $v[$tag]=$value;
                        }
                        $weather_arr[] = $weather;
                    }
                }
                foreach($temperature_city as $temperature => &$v){
                    if(in_array($city,$v['cities'])){
                        if(isset($v[$tag])){
                            $v[$tag]+=$value;
                        }else{
                            $v[$tag]=$value;
                        }
                        $temperature_arr[] = $temperature;
                    }
                }
                foreach($pm25_city as $pm25 => &$v){
                    if(in_array($city,$v['cities'])){
                        if(isset($v[$tag])){
                            $v[$tag]+=$value;
                        }else{
                            $v[$tag]=$value;
                        }
                        $pm25_arr[] = $pm25;
                    }
                }
            }
                
            $values = array_merge($values,[
                'weather' => implode(',',array_unique($weather_arr)),
                'temperature' => implode(',',array_unique($temperature_arr)),
                'pm25' => implode(',',array_unique($pm25_arr)),
            ]);
        }
        
        return compact('weather_city','temperature_city','pm25_city','cities');
    }
    
    /*
     * 获取关注群的数据
     * {
         gid=>
     }
     */
    public function getConcernGroupsReport($startTime,$endTime){
        $titles = [
            'createActivity_group' => '活动',
            'runningData_group' => '跑步',
            'post_group' => '发帖',
            'quit_group' => '退群',
            'applyGroup_group' => '加群'
        ];
        
        $as_str = implode("','",array_keys($titles));
        $sql = "SELECT * FROM d_api_count WHERE a IN('$as_str') AND add_time BETWEEN $startTime AND $endTime";
        $rows = $this->logDb->getAll($sql);
        
        $groups = [];
        foreach($rows as $row){
            $values = json_decode($row['value'],true);
            
            $tag = $titles[$row['a']];
            foreach($values as $gid=>$v){
                if(isset($groups[$gid][$tag])){
                    $groups[$gid][$tag] += $v;
                }else{
                    $groups[$gid][$tag] = $v;
                }
            }
        }
        
        return $groups;
    }
    
    /*
     * 给特定日期的数据做标记
     */
    public function getMarkedLine($data){
        $dates = array_keys($data);
        $startTime = current($dates);
        $endTime = end($dates);
        $sql = "SELECT starttime FROM r_admin_remark WHERE starttime BETWEEN $startTime AND $endTime";
        $rows = $this->db->getAll($sql);
        $dates = [];
        foreach($rows as $row){
            $dates[] = $row['starttime'];
        }
        
        foreach($data as $date=>&$v){
            if(in_array($date,$dates)){
                $v = ['y'=>$v,'marker'=>['symbol'=>'url(http://www.hcharts.cn/demo/img/sun.png)']];
            }
        }
        return $data;
    }
    
    /*
     * 记录敏感词用户
     */
    public function logBadwords($badwords){
        $gid = common::request('gid','R');
        $uid = $this->base->uid;
        $user = $this->base->load('user')->getUserInfo($uid);
        $ip = common::getip();
        $city = $this->base->load('ip')->find($ip);
        
        $data = [
            'cat' => $gid ? '群组_'.$gid : '跑友秀帖子',
            'badwords' => $badwords,
            'news_id' => '',
            'qq' => $user['qq'],
            'phone' => $user['phone'],
            'register_time' => $user['addtime'],
            'register_ip' => isset($user['ip']) ? $user['ip'] : $ip,
            'uid' => $user['uid'],
            'nickname' => $user['nickname'],
            'ip' => $ip,
            'city' => (is_array($city) && $city[2]) ? $city[2] : '其他',
            'addtime' => time()
        ];
        $this->logDb->insertRowTable('r_badwords_log',$data);
    }
    
    /*
     * 获取敏感词记录
     */
    public function getBadwordsLog($stime,$etime){
        return $this->logDb->getAll("select * from r_badwords_log where addtime between $stime and $etime");
    }
}
?>
